package liu.de.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import liu.de.dto.Bean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

import static liu.de.config.RabbitMqConfig.QUEUE_DELAY;
import static liu.de.config.RabbitMqConfig.QUEUE_TEST;

/**
 * @author liude
 */

@Service
@Slf4j
public class RabbitService {

    private final ObjectMapper objectMapper;

    @Autowired
    public RabbitService(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @RabbitListener(queues = QUEUE_DELAY)
    public void onDelayMessage(Message message, Channel channel) {
        try {
            Bean bean = fromMessage(message, objectMapper);
            log.info("converted={}", bean);

        } catch (IOException e) {
            log.error("", e);
        }

        ack(message, channel);
    }

    @RabbitListener(queues = QUEUE_TEST)
    public void onMessage(Message message, Channel channel) {
        try {
            Bean bean = fromMessage(message, objectMapper);
            log.info("converted={}", bean);

        } catch (IOException e) {
            log.error("", e);
        }

        ack(message, channel);
    }

    private Bean fromMessage(Message message, ObjectMapper objectMapper) throws IOException {
        String json = new String(message.getBody());
        log.info("payload={}", json);
        return objectMapper.readValue(json, Bean.class);
    }

    private void ack(Message message, Channel channel) {
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            log.error("ack failed!", e);
        }
    }
}
